package com.study.demo.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

@Slf4j
public class PdfDemo {

    public static void main(String[] args) throws Exception {

        String filename = "D:/pdfTest/testTable3.pdf";

//        List<String> list = new ArrayList<>();
        java.util.List<Product> list = new ArrayList<>();
        list.add(new Product("用户1", "18001062635", "https://test.com1"));
        list.add(new Product("用户2", "18001062635", "https://test.com2"));
        list.add(new Product("用户3", "18001062635", "https://test.com3"));


        createPDF(filename, list);
        log.info("打印完成");

    }

    public static void createPDF(String filename, java.util.List<Product> list) throws IOException {

        Document document = new Document(PageSize.A4);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));

            document.addTitle("example of PDF");
            document.open();

            PdfPTable table = createTable(writer, list);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }


    public static PdfPTable createTable(PdfWriter writer, java.util.List<Product> list) throws DocumentException, IOException {

        PdfPTable table = new PdfPTable(3);//生成一个两列的表格
        PdfPCell cell;
        int size = 20;

        // 表头
        cell = new PdfPCell(new Phrase("姓名"));
        cell.setFixedHeight(size + 2);//设置高度
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("电话"));
        cell.setFixedHeight(size + 2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("报告地址"));
        cell.setFixedHeight(size + 2);
        table.addCell(cell);

        for (Product product : list) {

            cell = new PdfPCell(new Phrase(product.getUserName()));
            cell.setFixedHeight(size);//设置高度
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(product.getPhone()));
            cell.setFixedHeight(size);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(product.getReportUrl()));
            cell.setFixedHeight(size);
            table.addCell(cell);
        }

        return table;
    }


}
